<?php
/*
haytemplate - Simple PHP template Class.
Copyright (c) 2008-2009 Hay Kranen <www.haykranen.nl> <hay at bykr dot org>
version 1.0

== Use ==
A simple way to enable value replacement in a template. Build your templates 
like this:

<p>{value}</p>

Then load the class and replace your values
try {
    $t = new Template("mytemplate.html");
} catch Exception($e) {
    die("Something went wrong..." . $e->getMessage());
}

$t->set(array(
    "value" => "Another value"
));

echo $t->getOutput();
  
== License (MIT/X11) ==

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
class Template {
    private $template;
    private $output;

    function __construct($template) {
        $template = ABSPATH . "templates/" . $template . ".html";
        
        if(!file_exists($template)) {
            throw new Exception("Could not get the contents of your template");
            return;
        }                    
        $this->template = file_get_contents($template);
        
        if(!$this->get_tags()) {
            throw new Exception("Could not parse your template");
            return;
        }
    }

    private function get_tags() {
        preg_match_all("!\{([^{]*)\}!", $this->template, $matches);
        if(!empty($matches)) {
            $this->tags = $matches;
            return true;
        } else {
            return false;
        }
    }

    public function set($data) {
        $values = $this->tags;
        for($i = 0; $i < count($values[0]); $i++) {
            $key   = trim($values[0][$i], "{}");
            $value = &$values[1][$i];
            
            // If this tag exists in our $data array, replace it
            // else, replace it with ''
            $value = isset($data[$key]) ? $data[$key] : "";
        }

        // Replace the template now
        $this->output = str_replace($values[0], $values[1], $this->template);
    }

    public function getOutput() {
        return $this->output;
    }
}
?>